package com.zl.ble.client;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.zl.ble.BLEConstants;
import com.zl.ble.ReceiveListener;
import com.zl.ble.connect.ConnectedListener;
import com.zl.ble.connect.ConnectedThread;
import com.zl.ble.util.StringUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;


public class BluetoothClient {
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private BluetoothSocket mBluetoothSocket;
    private int mState;
    private String addressMac;
    private ReceiveListener mReceiveListener;


    public BluetoothClient() {
        cleanConnect();
    }

    public void setState(int mState) {
        this.mState = mState;
    }

    public int getState() {
        return mState;
    }

    public void setReceiveListener(ReceiveListener mReceiveListener) {
        this.mReceiveListener = mReceiveListener;
    }

    public synchronized void cleanConnect() {
        Log.d(BLEConstants.TAG, "cleanConnect");
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        mState = BLEConstants.STATE_NONE;
    }

    public synchronized void connect(String addressMac) {
        Log.d(BLEConstants.TAG, "connect to: " + addressMac);
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        mConnectThread = new ConnectThread(addressMac);
        mConnectThread.start();
    }

    public synchronized void connected() {
        Log.d(BLEConstants.TAG, "connected");
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        mConnectedThread = new ConnectedThread(mBluetoothSocket);
        mConnectedThread.setConnectedListener(mConnectedListener);
        mConnectedThread.start();
//        ZHandlerUtil.getThreadHandler().post(mConnectService);
    }


    public synchronized void reConnect() {
        Log.d(BLEConstants.TAG, "connect to: " + addressMac);
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        mConnectThread = new ConnectThread(addressMac);
        mConnectThread.start();
    }

    private ConnectedListener mConnectedListener = new ConnectedListener() {

        @Override
        public void onReceive(byte[] msg) {
            Log.i(BLEConstants.TAG, "onReceive：" + Arrays.toString(msg));
            if (null != mReceiveListener && null != msg && msg.length > 0) {
                mReceiveListener.onReceive(msg);
                mReceiveListener.onReceiveLog(new String(msg));
            }
        }

        @Override
        public void onConnected() {
            addressMac = mBluetoothSocket.getRemoteDevice().getAddress();
        }

        @Override
        public void onDisConnected(Exception e) {
            if (mState != BLEConstants.STATE_CONNECTING && StringUtil.isEmpty(addressMac)) {
                reConnect();
            }
        }
    };

//    public Runnable mConnectService = new Runnable() {
//        @Override
//        public void run() {
//            if (mState != BLEConstants.STATE_CONNECTED) {
//                ZHandlerUtil.getThreadHandler().postDelayed(mConnectService, BLEConstants.CHECK_ACTIVE_COOL_TIME);
//            } else {
//                ZHandlerUtil.getThreadHandler().removeCallbacks(mConnectService);
//            }
//        }
//    };


    public boolean write(byte[] message) {
        ConnectedThread r;
        synchronized (BluetoothClient.this) {
            r = mConnectedThread;
        }
        if (r != null) {
            return r.write(message);
        }
        return false;
    }

    private class ConnectThread extends Thread {
        public ConnectThread(String addressMac) {
            BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addressMac);
            try {
//                mBluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(BLEConstants.SPP_UUID));
                mBluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(BLEConstants.SPP_UUID));
            } catch (IOException e) {
                Log.e(BLEConstants.TAG, "create() failed", e);
            }
            mState = BLEConstants.STATE_CONNECTING;
        }

        public void run() {
            setName("DEVICE_CONNECT");
            BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
            try {
                mBluetoothSocket.connect();
                if (null != mReceiveListener) {
                    mReceiveListener.onConnect();
                }
            } catch (IOException e) {
                try {
                    mBluetoothSocket.close();
                } catch (IOException e2) {
                    Log.e(BLEConstants.TAG, "unable to close() " + " socket during connection failure", e2);
                }
                Log.e(BLEConstants.TAG, "unable to close() " + " socket during connection failure", e);
                return;
            }
            connected();
        }

        public void cancel() {

        }
    }
}
